﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using mtg_trader.Database;
using mtg_trader.Database.DbSets;
using mtg_trader.Web.Models.Account;
using System.Security.Cryptography;

namespace mtg_trader.Web.Controllers
{
    public class AccountController : Controller
    {
        
        public ActionResult LogOn(UserModel model)
        {
            var sha1Hash = SHA1.Create();
            User user;
            using (var context = new MtgContext())
            {
                var bytes = Encoding.UTF8.GetBytes(model.Password);
                var password = sha1Hash.ComputeHash(bytes).ToString();
                user = context.Users.FirstOrDefault(
                    u => (u.DisplayName == model.DisplayName || u.Email == model.DisplayName) && u.Password == password);
            }
            
            if (user != null) FormsAuthentication.SetAuthCookie(user.DisplayName, true);

            return new JsonResult
                {
                    Data = new {IsSuccess = user != null}
                };
        }

    }
}
